import datetime
import logging
import re
from concurrent.futures import ThreadPoolExecutor
import concurrent.futures

import accountApi
import config
import json

from DB import MySQLUtils

dbUtil = MySQLUtils.DBUtil()
account = '18788828938'
headers = accountApi.getHeaders(account)
result_folder = 'd:\\Project\\Python\\fang\\resource\\detail_json'

def process_house(house_id):
    # url = f'http://erp.fangline.cn/house/get-house-details-by-id.json?houseId={house_id}'
    # response = requests.post(url, headers=headers)

    house_file = result_folder + f'\\{house_id}.json'
    # 读取文件中的 JSON 数据
    with open(house_file, 'r', encoding='utf-8') as file:
        house = json.load(file)

        if (house):
            try:
                create_time = house['house']['createTime']

                # 将时间戳转换为 datetime 对象
                timestamp = create_time / 1000  # 将毫秒转换为秒
                dt = datetime.datetime.fromtimestamp(timestamp)

                # 将 datetime 对象格式化为指定格式的字符串
                formatted_date = dt.strftime('%Y-%m-%d %H:%M:%S')

                sql = "update house set create_time = %s where house_id = %s;"
                values = (
                    formatted_date,
                    house_id
                )

                dbUtil.saveAsValues(sql, values)

                print(f"写入记录 {house_id} ")
            except Exception as e:
                logging.error(e)

def main():
    # 获取所有房源的 ID
    house_ids = dbUtil.get_all(
        "select house_id from house where create_time is null")

    max_threads = 10
    for house_id in house_ids:
        process_house(house_id[0])
        # with concurrent.futures.ThreadPoolExecutor(max_workers=max_threads) as executor:
        #     executor.map(process_house, house_id[0])
        # with ThreadPoolExecutor(max_workers=max_threads) as executor:
        #   executor.map(process_house, house_id[0])


# 主函数
if __name__ == '__main__':
    current_date = datetime.datetime.now().strftime("%Y%m%d")
    log_file = f"logs/{current_date}.log"
    config.setup_logging(log_file)

    main()
